package mylab.io.store.rxtx;

import com.google.common.base.Preconditions;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.rxtx.RxtxChannel;
import io.netty.channel.rxtx.RxtxChannelConfig;
import io.netty.channel.rxtx.RxtxChannelOption;
import io.netty.channel.rxtx.RxtxDeviceAddress;
import mylab.io.base.model.Msg;
import mylab.io.core.AbstractClientDas;
import mylab.io.core.context.DefaultCC;
import mylab.io.store.rxtx.property.RxtxProperties;
import mylab.utils.common.StringUtil;

@SuppressWarnings({"deprecation"})
public class RxtxDas<M extends Msg> extends AbstractClientDas<RxtxProperties, M, RxtxCodec<M>, ByteBuf> {

    public RxtxDas(DefaultCC<RxtxProperties, M> rxtxInfoMDefaultCC, RxtxCodec<M> codec) {
        super(rxtxInfoMDefaultCC, codec);
    }

    @Override
    protected ChannelFuture actualStart() throws Exception {
        String portName = properties.getSerialPort();
        Preconditions.checkState(StringUtil.isNotEmpty(portName), "未配置串口");
        Preconditions.checkState(RxtxUtil.contains(portName), "无此串口:" + portName);

        masterLoop = new OioEventLoopGroup();
        RxtxDeviceAddress rxtxDeviceAddress = new RxtxDeviceAddress(portName);

        bootstrap = new Bootstrap();
        bootstrap.group(masterLoop)
                .channel(RxtxChannel.class)
                .option(RxtxChannelOption.BAUD_RATE, properties.getBaudRate())
                .option(RxtxChannelOption.DATA_BITS, RxtxChannelConfig.Databits.valueOf(properties.getDataBits()))
                .option(RxtxChannelOption.STOP_BITS, RxtxChannelConfig.Stopbits.valueOf(properties.getStopBits()))
                .option(RxtxChannelOption.PARITY_BIT, RxtxChannelConfig.Paritybit.valueOf(properties.getParity()))
                .handler(codec.getChannelInitializer());


        return bootstrap.connect(rxtxDeviceAddress);
    }

}
